package com.projx.accounting.service;

import com.projx.accounting.module.User;
import com.projx.accounting.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 简单的用户服务，使用内存存储实现基本 CRUD，便于早期开发以及单元测试。
 */
@Service
public class UserService {
    private final UserRepository repo;

    public UserService(UserRepository repo) {
        this.repo = repo;
    }

    public User create(User user) {
        return repo.save(user);
    }

    public User create(String username, String email) {
        User u = User.create(username, email);
        return repo.save(u);
    }

    public Optional<User> findById(String id) {
        return repo.findById(id);
    }

    public List<User> listAll() {
        return repo.findAll();
    }

    public User update(User user) {
        if (user.getId() == null) throw new IllegalArgumentException("id required for update");
        return repo.save(user);
    }

    public boolean delete(String id) {
        if (!repo.existsById(id)) return false;
        repo.deleteById(id);
        return true;
    }

    public Optional<User> findByUsername(String username) {
        return repo.findByUsername(username);
    }

    public Optional<User> authenticate(String username, String password) {
        return findByUsername(username).filter(u -> u.getPassword() != null && u.getPassword().equals(password));
    }
}
